package com.wl156.services;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;

import android.app.AlertDialog;
import android.app.IntentService;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

import com.wl156.model.WebServiceClient;
import com.wl156.utils.Web;

public class DownloadIntentService extends IntentService {
	private static final String TAG = DownloadIntentService.class
			.getSimpleName();

	public DownloadIntentService() {
		super("DownloadIntentService");
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		String url = intent.getStringExtra("url");

		String downloadUrl = WebServiceClient.BASE_URL + url;

		Log.d(TAG, "downloadUrl: " + downloadUrl);

		new DownloadApkTask(this, downloadUrl).execute();
	}

	class DownloadApkTask extends AsyncTask<Void, Integer, Integer> {
		private static final int OK = 1;
		private static final int CANCEL = 2;
		private static final int FAILED = 3;

		private static final String APK_NAME = "wl156.apk";

		private Context mContext;
		private String mUrl;

		public DownloadApkTask(Context context, String url) {
			mContext = context;
			mUrl = url;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();

		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
			Log.d(TAG, "onCancelled");

			mContext.deleteFile(APK_NAME);

			AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
			builder.setTitle("更新失败");
			builder.setMessage("您取消了下载进程！");
			builder.setNeutralButton("确定",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
						}
					}).show();
		}

		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);

			Log.d(TAG, "result: " + result);

			if (result == FAILED) {
				// AlertDialog.Builder builder = new
				// AlertDialog.Builder(mContext);
				// builder.setTitle("更新失败");
				// builder.setMessage("更新失败");
				// builder.setNeutralButton("确定",
				// new DialogInterface.OnClickListener() {
				// @Override
				// public void onClick(DialogInterface dialog,
				// int which) {
				// }
				// }).show();
				Toast.makeText(DownloadIntentService.this, "更新失败",
						Toast.LENGTH_LONG).show();
			} else {
				Intent intent = new Intent();
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				String fileAbsPath = "file://"
						+ mContext.getFilesDir().getAbsolutePath() + "/"
						+ APK_NAME;
				intent.setAction(android.content.Intent.ACTION_VIEW);
				intent.setDataAndType(Uri.parse(fileAbsPath),
						"application/vnd.android.package-archive");
				mContext.startActivity(intent);
			}
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
		}

		@Override
		protected Integer doInBackground(Void... params) {
			Web web = new Web(mContext);
			try {
				HttpGet get = new HttpGet(mUrl);
				HttpResponse response = web.getClient().execute(get);
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					long contentLength = entity.getContentLength();
					byte[] buffer = new byte[4 * 1024];
					InputStream is = null;
					FileOutputStream fos = null;
					int readNum;
					int readTotal = 0;
					try {
						fos = mContext.openFileOutput(APK_NAME,
								Context.MODE_WORLD_READABLE);
						is = entity.getContent();
						while ((readNum = is.read(buffer)) != -1) {
							if (isCancelled()) {
								return CANCEL;
							}
							fos.write(buffer, 0, readNum);
							readTotal += readNum;
							
							

							// update progress
							int progress = (int) (readTotal * 100 / contentLength);
//							publishProgress(progress);
							
							Log.d(TAG, "progress: " + progress);
						}
						fos.flush();
					} catch (IOException e) {
						Log.d(TAG, e.getMessage(), e);
						return FAILED;
					} finally {
						try {
							if (fos != null) {
								fos.close();
							}
							if (is != null) {
								is.close();
							}
						} catch (IOException e) {
							Log.d(TAG, e.getMessage(), e);
						}
					}
				}
				return OK;
			} catch (Exception e) {
				Log.d(TAG, e.toString());
				return FAILED;
			}
		}
	}
}
